<?php
namespace app\admin\logic;

use app\common\logic\Base;
use think\Db;
use think\facade\App;

class BehaviorLog extends Base {
    
    /**
     * @desc 订单列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($params) {
        $where = [];
        if($params['controller']) {
            $where[] = ['bl_controller', '=', $params['controller']];
        }
    
        if($params['action']) {
            $where[] = ['bl_action', '=', $params['action']];
        }
        
        if($params['memberName']) {
            $memberId = App::model('AuthMember')
                ->where('am_username', 'like', '%'.$params['memberName'].'%')
                ->value('am_member_id');
            if($memberId) {
                $where[] = ['bl_member_id', '=', $memberId];
            }
        }
        
        $list = App::model('BehaviorLog')
            ->where($where)
            ->order('bl_id', 'desc')
            ->paginate($params['pageSize']);
    
        $pagination = $list->render();
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'bl');
            
            $memberIds = array_unique(array_column($list, 'memberId'));
            $memberInfo = App::model('AuthMember')
                ->where('am_member_id', 'in', $memberIds)
                ->column('am_username', 'am_member_id');
            
            foreach ($list as $k => $v) {
                $list[$k]['memberName'] = $memberInfo[$v['memberId']];
            }
        }

        return [
            'list'         => $list,
            'params'       => $params,
            'pagination'   => $pagination
        ];
    }
}